package com.labofjet.blogv3.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.labofjet.blogv3.facade.ManageFacade;
import com.labofjet.blogv3.model.Artical;
import com.labofjet.blogv3.model.Category;
import com.labofjet.blogv3.model.History;
import com.labofjet.blogv3.model.User;

/**
 * 后台管理的Controller
 * 
 * @author Jet
 * @version 2014.8
 * 
 */
@Controller
public class ManageController {
    @Autowired
    private ManageFacade manageFacade;

    private static final Logger LOGGER = LoggerFactory.getLogger(ManageController.class);

    @ModelAttribute
    public void autoLogin(HttpSession session) {
        if (session.getAttribute("user") == null && SecurityUtils.getSubject().getPrincipal() != null) {
            long userId = (long) SecurityUtils.getSubject().getPrincipal();
            User u = manageFacade.findUser(userId);
            session.setAttribute("user", u);
        }
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(User u) {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login2(String username, String password, HttpSession session, boolean rememberMe) {
        try {
            SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password, rememberMe));
        } catch (Exception e) {
            LOGGER.error("登陆失败,错误原因为 {}", e);
            return "redirect:/login";
        }
        User u = manageFacade.findUser(username, password);
        session.setAttribute("user", u);
        return "redirect:/";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession s) {
        s.removeAttribute("user");
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }

    /**
     * 新增历史页面
     * 
     * @param
     * @return
     */
    @RequestMapping(value = "/manage/history/add", method = RequestMethod.GET)
    public String history_add() {
        return "history-add";
    }

    /**
     * 新增历史操作
     * 
     * @param h
     * @return
     */
    @RequestMapping(value = "/manage/history/add", method = RequestMethod.POST)
    public String history_add2(History h) {
        manageFacade.save(h);
        return "redirect:/";
    }

    /**
     * 新增文章页面
     * 
     * @param m
     * @return
     */
    @RequestMapping(value = "/manage/artical/add", method = RequestMethod.GET)
    public String artical_add(Model m) {
        m.addAttribute("categories", manageFacade.findAllCategories());
        return "artical-add";
    }

    /**
     * 新增文章操作
     * 
     * @param artical
     * @param id_user
     * @param category
     * @return
     */
    @RequestMapping(value = "/manage/artical/add", method = RequestMethod.POST)
    public String artical_add2(Artical artical, Long[] category, HttpSession session) {
        User u = (User) session.getAttribute("user");
        artical.setAuthor(u);
        artical.setDate(new Date());
        if (category != null)
            for (long id : category) {
                Category c = new Category();
                c.setId(id);
                c.getArticals().add(artical);
                artical.getCategories().add(c);
            }
        manageFacade.save(artical);
        return "redirect:/";
    }

    /**
     * 新增标签页面
     * 
     * @return
     */
    @RequestMapping(value = "/manage/category/add", method = RequestMethod.GET)
    public String category_add() {
        return "category-add";
    }

    /**
     * 新增标签操作
     * 
     * @return
     */
    @RequestMapping(value = "/manage/category/add", method = RequestMethod.POST)
    public String category_add2(Category c) {
        this.manageFacade.save(c);
        return "redirect:/";
    }

    /**
     * 删除标签页面
     * 
     * @param m
     * @return
     */
    @RequestMapping(value = "/manage/category/delete", method = RequestMethod.GET)
    public String category_delete(Model m) {
        m.addAttribute("categories", manageFacade.findAllCategories());
        return "category-delete";
    }

    /**
     * 删除标签操作
     * 
     * @return
     */
    @RequestMapping(value = "/manage/category/delete", method = RequestMethod.POST)
    public String category_delete2(long id) {
        manageFacade.deleteCategory(id);
        return "redirect:/";
    }

    /**
     * 修改文章页面
     * 
     * @param m
     * @return
     */
    @RequestMapping(value = "/manage/artical/update/{id}", method = RequestMethod.GET)
    public String artical_update(Model m, @PathVariable long id) {
        Artical a = manageFacade.findArtical(id);
        m.addAttribute("artical", a);
        m.addAttribute("categories", manageFacade.findAllCategories());
        return "artical-update";
    }

    /**
     * 修改文章操作
     * 
     * @param artical
     * @param id_user
     * @param category
     * @return
     */
    @RequestMapping(value = "/manage/artical/update/{id}", method = RequestMethod.POST)
    public String artical_update2(Artical artical, Long[] category) {
        if (category != null) {
            for (long id : category) {
                Category c = new Category();
                c.setId(id);
                c.getArticals().add(artical);
                artical.getCategories().add(c);
            }
        }
        manageFacade.updateArtical(artical);
        return "redirect:/";
    }

    @RequestMapping(value = "/manage/artical/delete/{id}")
    public String artical_delete(@PathVariable long id) throws IOException {
        manageFacade.deleteArtical(id);
        return "redirect:/";
    }
}